package middleware

import (
	"net/http"
	"simple-crm/services"
	"strconv"
	
	"github.com/gin-gonic/gin"
)

type PermissionMiddleware struct {
	permissionService *services.PermissionService
}

func NewPermissionMiddleware(permissionService *services.PermissionService) *PermissionMiddleware {
	return &PermissionMiddleware{
		permissionService: permissionService,
	}
}

// 检查权限的中间件
func (m *PermissionMiddleware) RequirePermission(permission string) gin.HandlerFunc {
	return func(c *gin.Context) {
		// 获取当前用户ID
		userIDStr, exists := c.Get("user_id")
		if !exists {
			c.JSON(http.StatusUnauthorized, gin.H{"error": "未登录"})
			c.Abort()
			return
		}
		
		userID, ok := userIDStr.(uint)
		if !ok {
			c.JSON(http.StatusUnauthorized, gin.H{"error": "用户信息无效"})
			c.Abort()
			return
		}
		
		// 检查权限
		if !m.permissionService.HasPermission(userID, permission) {
			c.JSON(http.StatusForbidden, gin.H{"error": "权限不足"})
			c.Abort()
			return
		}
		
		c.Next()
	}
}

// 检查权限的中间件（用于页面，返回HTML错误页面）
func (m *PermissionMiddleware) RequirePermissionForPage(permission string) gin.HandlerFunc {
	return func(c *gin.Context) {
		// 获取当前用户ID
		userIDStr, exists := c.Get("user_id")
		if !exists {
			c.HTML(http.StatusUnauthorized, "errors/401.html", gin.H{
				"title": "未登录",
				"message": "请先登录",
			})
			c.Abort()
			return
		}
		
		userID, ok := userIDStr.(uint)
		if !ok {
			c.HTML(http.StatusUnauthorized, "errors/401.html", gin.H{
				"title": "用户信息无效",
				"message": "用户信息无效",
			})
			c.Abort()
			return
		}
		
		// 检查权限
		if !m.permissionService.HasPermission(userID, permission) {
			c.HTML(http.StatusForbidden, "errors/403.html", gin.H{
				"title": "权限不足",
				"message": "您没有访问此页面的权限",
				"user": c.MustGet("user"),
			})
			c.Abort()
			return
		}
		
		c.Next()
	}
}

// 检查多个权限中的任意一个
func (m *PermissionMiddleware) RequireAnyPermission(permissions ...string) gin.HandlerFunc {
	return func(c *gin.Context) {
		userIDStr, exists := c.Get("user_id")
		if !exists {
			c.JSON(http.StatusUnauthorized, gin.H{"error": "未登录"})
			c.Abort()
			return
		}
		
		userID, ok := userIDStr.(uint)
		if !ok {
			c.JSON(http.StatusUnauthorized, gin.H{"error": "用户信息无效"})
			c.Abort()
			return
		}
		
		// 检查是否有任意一个权限
		hasPermission := false
		for _, permission := range permissions {
			if m.permissionService.HasPermission(userID, permission) {
				hasPermission = true
				break
			}
		}
		
		if !hasPermission {
			c.JSON(http.StatusForbidden, gin.H{"error": "权限不足"})
			c.Abort()
			return
		}
		
		c.Next()
	}
}

// 操作日志中间件
func (m *PermissionMiddleware) LogOperation(action, resource string) gin.HandlerFunc {
	return func(c *gin.Context) {
		c.Next() // 先执行业务逻辑
		
		// 记录操作日志
		if userIDStr, exists := c.Get("user_id"); exists {
			if userID, ok := userIDStr.(uint); ok {
				var resourceID *uint
				if idStr := c.Param("id"); idStr != "" {
					if id, err := strconv.ParseUint(idStr, 10, 32); err == nil {
						resourceIDUint := uint(id)
						resourceID = &resourceIDUint
					}
				}
				
				description := action + " " + resource
				if resourceID != nil {
					description += " (ID: " + strconv.Itoa(int(*resourceID)) + ")"
				}
				
				m.permissionService.LogOperation(
					userID,
					action,
					resource,
					resourceID,
					description,
					c.ClientIP(),
					c.GetHeader("User-Agent"),
				)
			}
		}
	}
}